package com.situ.stmall.admin.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.situ.stmall.admin.entity.APIResult;
import com.situ.stmall.admin.entity.Root;
import com.situ.stmall.admin.service.RootService;
/**
 * 管理员
 * @author 14435
 *
 */
@RestController
@RequestMapping("/api/roots")
@CrossOrigin(origins = {"*"})
public class RootController {
	@Autowired
	private RootService rootService;
	/**
	 * 登录
	 */
	@GetMapping
	public APIResult login(Root root,String vercode,
			HttpSession session) {
		// 1.获取参数
		//判断vercode是否正确
		// 2.调用service
		APIResult apiResult=new APIResult();
		try {
			Root loginRoot= rootService.login(root);
			loginRoot.setPassword(null);
			session.setAttribute("root", loginRoot);
			apiResult.setStatus(200);
			apiResult.setMsg("成功");
			apiResult.setData(loginRoot);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			apiResult.setStatus(404);
			apiResult.setMsg(e.getMessage());
		}
		// 3.返回数据
		
		return apiResult;
	}
	/**
	 * 注册
	 */
	@GetMapping
	public APIResult register() {
		
		APIResult apiResult=new APIResult();
		
		return apiResult;
	}
	/**
	 * 退出
	 */
	@DeleteMapping
	public APIResult logout(HttpSession session) {
		session.invalidate();
		APIResult apiResult=new APIResult();
		apiResult.setMsg("退出");
		apiResult.setStatus(204);
		return apiResult;
	}
	
	/**
	 * 修改
	 */
	@PutMapping
	public APIResult edit(Root root1,HttpSession session) {
		APIResult apiResult=new APIResult();
		Root root = rootService.edit(root1);
		if (root != null) {
			session.setAttribute("root", root1);
			apiResult.setStatus(201);
			apiResult.setData(root);
		} else {
			apiResult.setStatus(404);
			apiResult.setData("用户不存在");
		}
		return apiResult;
	}
}
